// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const bookCoverUrl = 'https://ov-library-1316830564.cos.ap-guangzhou.myqcloud.com/bookCover%2F'
const defaultCover = '/resource/images/defaultCover.png'

Page({

    data: {
        avatarUrl: defaultAvatarUrl,
        borrowingCount: 0,
        overdueCount: 0,
        totalCount: 0,
        userInfo: [],
        userAvatar: 'https://ov-library-1316830564.cos.ap-guangzhou.myqcloud.com/userAvatar/',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.clickLogin();
        this.getUserInfoByOpenid();
        this.getBookInfo();
        this.borrowingCount();
        this.overdueCount();
        this.totalCount();
    },

    onShow(){
        console.log("执行了onshow")
        this.onLoad()
    },

    bindViewTap() {
        wx.navigateTo({
            url: '../logs/logs'
        })
    },
    onChooseAvatar(e) {
        const {
            avatarUrl
        } = e.detail
        const {
            nickName
        } = this.data.userInfo
        this.setData({
            "userInfo.avatarUrl": avatarUrl,
            hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
        })
    },
    onInputChange(e) {
        const nickName = e.detail.value
        const {
            avatarUrl
        } = this.data.userInfo
        this.setData({
            "userInfo.nickName": nickName,
            hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
        })
    },
    getUserProfile(e) {
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        wx.getUserProfile({
            desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                console.log(res)
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        })
    },
    onClickSearch(){
        wx.navigateTo({
          url: '/pages/books/search/search',
        })
    },

    clickLogin: function () {

        const that = this;

        wx.login({
            success: (res) => {
                // console.log("js_code", res.code)
                if (res.code) {
                    //发起网络请求
                    wx.request({
                        url: 'http://localhost:8080/user/getWxInfo',
                        method: 'post',
                        data: {
                            code: res.code
                        },
                        header: {
                            'content-type': 'application/json' // 明确指定JSON格式
                        },
                        success: (res) => {
                            this.setData({
                                wxInfo: res.data
                            });
                            wx.setStorageSync('openid', res.data.openid)
                            // console.log("userId:" + wx.getStorageSync('userId'))
                            if (!wx.getStorageSync('userId')) {
                                this.onLoad()
                            }
                            if (!this.data.borrowingCount) {
                                this.onLoad()
                            }
                        },
                    })
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            }
        })
    },

    //通过openid获取用户信息
    getUserInfoByOpenid: function () {

        const that = this;

        wx.request({
            url: 'http://localhost:8080/user/getUserInfo',
            method: 'post',
            data: {
                openId: wx.getStorageSync('openid')
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: (res) => {
                this.setData({
                    userInfo: res.data
                });
                wx.setStorageSync('userName', res.data.userName)
                wx.setStorageSync('userId', res.data.userId)
                wx.setStorageSync('userInfo', res.data)
            }
        })
    },

    //获取图书信息
    getBookInfo: function () {
        wx.request({
            url: 'http://localhost:8080/books/hotBooks',
            method: 'get',
            data: {
                page: 1,
                limit: 9,
            },
            header: {
                'content-type': 'application/json'
            },
            success: (res) => {
                const bookList = res.data.data.map(book => {
                    const cover = `${bookCoverUrl}${book.isbn}.jpg`;
                    return {
                        id: book.bookId,
                        cover: cover,
                        title: book.bookTitle
                    };
                });

                this.setData({
                    bookList: bookList
                })
            }
        })
    },

    // 图片加载失败回调
    updateImageError(e) {
        const index = e.currentTarget.dataset.index; // 获取当前图片索引
        const newBookList = this.data.bookList.map((item, i) => {
            if (i === index) {
                // 仅修改加载失败的条目
                return {
                    ...item,
                    cover: defaultCover
                };
            }
            return item;
        });
        this.setData({
            bookList: newBookList
        });
    },

    goToBookDetail(event) {
        console.log("event:"+event)
        const bookId = event.currentTarget.dataset.id;
        wx.navigateTo({
          url: `/pages/books/detailed/detailed?id=${bookId}`
        });
      },

      //查询借阅数量
    borrowingCount(){
        wx.request({ 
            url: 'http://localhost:8080/borrowRecord/queryBorrowingCount?userId=' + wx.getStorageSync('userId'),
            method: 'GET',
            success: (res) => {
                this.setData({
                    borrowingCount: res.data.data
                });
            },
        });
    },

    //查询逾期数量
    overdueCount(){
        wx.request({ 
            url: 'http://localhost:8080/borrowRecord/queryOverdueCount?userId=' + wx.getStorageSync('userId'),
            method: 'GET',
            success: (res) => {
                this.setData({
                    overdueCount: res.data.data
                });
            },
        });
    },

     //查询总借阅数
     totalCount(){
        wx.request({ 
            url: 'http://localhost:8080/borrowRecord/queryTotalCount?userId=' + wx.getStorageSync('userId'),
            method: 'GET',
            success: (res) => {
                this.setData({
                    totalCount: res.data.data
                });
            },
        });
    },

    //跳转到我的借阅页面
    onBorrowed(){
        wx.navigateTo({
          url: '/pages/home/myBorrowing/myBorrowing',
        })
    },

    viewAllBooks(){
        wx.switchTab({
          url: '/pages/books/index/index',
        })
    }

})